package com.shinhye.mobilelottery.engine.impl;

import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.shinhye.mobilelottery.ConstantValue;
import com.shinhye.mobilelottery.engine.BaseEngine;
import com.shinhye.mobilelottery.engine.CommonInfoEngine;
import com.shinhye.mobilelottery.net.protocol.Message;
import com.shinhye.mobilelottery.net.protocol.element.IssueInfoElement;
import com.shinhye.mobilelottery.utils.DES;

public class CommonInfoEngineImpl extends BaseEngine implements CommonInfoEngine {

	@Override
	public Message getIssuesInfo(int lotteryid) {
		IssueInfoElement element = new IssueInfoElement();
		element.getLotteryid().setValue(lotteryid + "");
		Message message = new Message();
		String xml = message.getXml(element);
		
		Message res = getResult(xml);
		
		if(res != null) {
			DES des = new DES();
			String wholebody = "<body>" + des.authcode(res.getBody().getBodyInfo(), "ENCODE", ConstantValue.DES_KEY) + "</body>";
			try {
				handleOElement(res, wholebody);
				
				IssueInfoElement issueEle = new IssueInfoElement();
				res.getBody().getElements().add(issueEle);
				
				XmlPullParser parser = Xml.newPullParser();
				StringReader reader = new StringReader(wholebody);
				parser.setInput(reader);
				int type = parser.getEventType();
				while(type != XmlPullParser.END_DOCUMENT) {
					switch(type) {
					case XmlPullParser.START_TAG:
						if("lotteryname".equals(parser.getName())) {
							issueEle.getLotteryname().setValue(parser.nextText());
						} else if("issue".equals(parser.getName())) {
							issueEle.getIssue().setValue(parser.nextText());
						} else if("lasttime".equals(parser.getName())) {
							issueEle.getLasttime().setValue(parser.nextText());
						}
						break;
					}
					type = parser.next();
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return res;
		}
		return null;
	}

}
